Popular Searches
Popular Course Categories
Popular Courses

Implementing Push Notifications with Firebase Cloud Messaging and APNs

Implementing Push Notifications with Firebase Cloud Messaging and APNs

Firebase Integration and Cloud Services

Implementing Push Notifications with Firebase Cloud Messaging and APNs

Course: iOS App Development

Topic: Implementing Push Notifications with Firebase Cloud Messaging and APNs

Course Link: iOS App Development Training – JustAcademy

Demo Link: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction to Push Notifications in iOS

Push notifications are messages sent from a server to a mobile application, allowing users to receive updates even when the app is running in the background or is not currently open. In iOS development, push notifications are commonly used for chat messages, order updates, reminders, promotional announcements, account alerts, and other time-sensitive information.

Firebase Cloud Messaging (FCM) provides a cross-platform messaging service that helps developers send notifications to registered app instances. On Apple platforms, FCM works with Apple Push Notification service (APNs), which delivers remote notifications to Apple devices.

Implementing push notifications requires configuring the Firebase project, enabling the appropriate Apple capabilities, registering the app for notifications, handling notification permissions, and testing messages on a supported device.

2. Learning Objectives

  • Understand push notifications and their role in iOS applications.
  • Learn the difference between Firebase Cloud Messaging and APNs.
  • Configure Firebase and Apple Developer settings for push notifications.
  • Integrate Firebase Messaging into a Swift-based iOS project.
  • Request notification permission from users.
  • Register the application with APNs and obtain messaging identifiers.
  • Handle notifications received in the foreground and background.
  • Test notifications using the Firebase Console.
  • Understand common notification errors and troubleshooting techniques.
  • Apply security and performance best practices.

3. What Are Push Notifications?

A push notification is a message delivered to an application through a remote notification service. Unlike local notifications, which are scheduled by the app on the device, push notifications are initiated by an external server or messaging platform.

Examples of Push Notifications

  • Messaging: A user receives an alert when a new chat message arrives.
  • E-commerce: An application notifies the user that an order has been shipped.
  • Education: Students receive reminders about classes, assignments, or exams.
  • Banking: A banking app alerts the user about account activity.
  • Travel: An airline app provides gate changes and flight updates.
  • Productivity: A task-management app sends reminders about deadlines.

4. Understanding Firebase Cloud Messaging and APNs

4.1 Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging is a messaging service used to send notifications and data messages to supported client applications. It offers tools for targeting individual app instances, groups of users, and subscribed topics. Developers can send messages through the Firebase Console or a trusted server environment.

4.2 Apple Push Notification service (APNs)

APNs is Apple's push notification delivery service. It routes remote notifications to Apple devices using Apple's notification infrastructure. An iOS application must be configured correctly with Apple Developer services before it can receive remote push notifications.

4.3 How FCM and APNs Work Together

When an application uses FCM on iOS, Firebase manages the messaging workflow while APNs provides the Apple-specific delivery channel.

  1. The developer configures an iOS app in Firebase and registers the app identifier with Apple Developer services.
  2. The app requests permission to display notifications.
  3. The app registers with APNs and receives an APNs device token when registration succeeds.
  4. Firebase Messaging associates the app instance with its Firebase messaging registration information.
  5. A trusted server or the Firebase Console sends a message through FCM.
  6. FCM routes the message through APNs to the target Apple device.
  7. iOS displays the notification or delivers the message to the app for handling, according to the payload and application state.

4.4 FCM vs APNs

Feature Firebase Cloud Messaging Apple Push Notification service
Primary role Messaging management and cross-platform delivery integration Apple-platform notification delivery
Platform support Multiple supported platforms Apple platforms
Message targeting Supports registration targets and topics Routes notifications using Apple device and app registration information
Configuration Firebase project and app configuration Apple Developer credentials, app identifier, and push capability
iOS relationship Uses APNs to deliver remote notifications Provides the Apple-specific delivery path

5. Prerequisites

Before implementing push notifications, ensure that the following requirements are met:

  • A Mac computer with a compatible version of Xcode.
  • An iOS application project written in Swift or SwiftUI.
  • An Apple Developer account with access to the necessary push notification configuration.
  • A Firebase project.
  • The application's correct bundle identifier.
  • The Firebase configuration file named GoogleService-Info.plist.
  • The Firebase Messaging SDK.
  • An APNs authentication key configured in Firebase.
  • A physical iPhone or another supported Apple test environment.

Important: A physical Apple device is the recommended testing environment for APNs-based push notifications. Simulator support depends on the host Mac, simulator architecture, and operating system version.

6. Creating a Firebase Project

The first step is to create a Firebase project and register the iOS application.

  1. Open the Firebase Console.
  2. Sign in with your Google account.
  3. Select Create a project or choose an existing project.
  4. Enter a suitable project name, such as iOSPushNotificationDemo.
  5. Complete the project setup instructions.
  6. Add an Apple application to the Firebase project.
  7. Enter the iOS bundle identifier exactly as it appears in Xcode.
  8. Download the GoogleService-Info.plist file.
  9. Add the configuration file to the correct target in Xcode.

The bundle identifier registered in Firebase must match the identifier configured for the iOS app. A mismatch can prevent the app from connecting to the intended Firebase configuration.

7. Installing the Firebase Messaging SDK

Firebase Messaging provides the APIs required to register the app with Firebase, manage messaging registration information, and handle incoming messages.

7.1 Using Swift Package Manager

  1. Open the project in Xcode.
  2. Choose File > Add Package Dependencies.
  3. Enter the official Firebase Apple SDK repository URL.
  4. Select the required Firebase products, including FirebaseMessaging and FirebaseCore.
  5. Add the packages to the appropriate application target.

Official repository: Firebase Apple SDK on GitHub.

7.2 Import Firebase Frameworks

import UIKit
import UserNotifications
import FirebaseCore
import FirebaseMessaging

FirebaseCore provides Firebase application configuration, FirebaseMessaging provides messaging functionality, and UserNotifications provides APIs for requesting permissions and managing notification presentation.

8. Enabling Push Notifications in Xcode

The iOS application must have the appropriate capabilities enabled before remote notifications can be delivered.

  1. Open the iOS project in Xcode.
  2. Select the application target.
  3. Open Signing & Capabilities.
  4. Confirm that the correct development team and bundle identifier are selected.
  5. Click + Capability.
  6. Add Push Notifications.
  7. If your app needs background notification processing, add Background Modes and enable the relevant options, such as Remote notifications, for the intended use case.
  8. Verify that the signing configuration and provisioning profile support push notifications.

Background Modes are not required for every visible alert notification. Enable background remote notifications when your application genuinely needs the corresponding background processing behavior.

9. Creating an APNs Authentication Key

APNs credentials allow Firebase to communicate with Apple's push notification infrastructure for your application.

9.1 Generate the Key

  1. Open the Apple Developer Account.
  2. Navigate to Certificates, Identifiers & Profiles.
  3. Open the Keys section.
  4. Create a new key and enable the Apple Push Notifications service (APNs) option.
  5. Register the key and download the generated private key file.
  6. Record the Key ID and the associated Apple Developer Team ID.
  7. Store the key securely. Apple does not provide unlimited opportunities to download the private key again.

9.2 Upload the Key to Firebase

  1. Open the Firebase Console and select your project.
  2. Navigate to Project settings.
  3. Open the Cloud Messaging tab.
  4. Find the iOS app configuration section.
  5. Upload the APNs authentication key file.
  6. Enter the Key ID and Team ID when requested.
  7. Save the configuration.

Use the correct key and identifiers for the Apple Developer team that owns the application. Keep private key files out of source control and do not include them in the distributed app.

10. Configuring Firebase in AppDelegate

Firebase must be initialized before using its messaging APIs. In a UIKit application, this setup is commonly performed in AppDelegate.swift.

10.1 Example AppDelegate.swift

import UIKit
import UserNotifications
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: UIResponder,
                   UIApplicationDelegate,
                   UNUserNotificationCenterDelegate,
                   MessagingDelegate {

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions:
            [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        FirebaseApp.configure()

        UNUserNotificationCenter.current().delegate = self
        Messaging.messaging().delegate = self

        return true
    }

    func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
        Messaging.messaging().apnsToken = deviceToken
        print("APNs registration succeeded.")
    }

    func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        print("APNs registration failed: \(error.localizedDescription)")
    }

    func messaging(
        _ messaging: Messaging,
        didReceiveRegistrationToken fcmToken: String?
    ) {
        guard let fcmToken = fcmToken else {
            return
        }

        print("FCM registration token received.")
        // Send the token to your trusted backend if needed.
        // Do not expose it in production logs.
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler:
            @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.banner, .sound, .badge])
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let userInfo = response.notification.request.content.userInfo
        print("Notification opened.")

        // Inspect trusted payload values and navigate as appropriate.
        print(userInfo)

        completionHandler()
    }
}

Note: This is a UIKit-style example. A SwiftUI application can use UIApplicationDelegateAdaptor to integrate an app delegate. If Firebase method swizzling is disabled, explicit APNs token mapping is important. If swizzling remains enabled, Firebase handles supported integration automatically, although the app still needs the correct notification delegates and configuration.

11. Requesting Notification Permission

iOS requires user authorization before displaying ordinary alert, sound, and badge notifications. Explain the benefit of notifications to users before displaying the system permission prompt when appropriate.

11.1 Request Authorization

import UserNotifications
import UIKit

func requestNotificationPermission() {
    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(
        options: [.alert, .sound, .badge]
    ) { granted, error in
        if let error = error {
            print("Permission request failed: \(error.localizedDescription)")
            return
        }

        DispatchQueue.main.async {
            if granted {
                UIApplication.shared.registerForRemoteNotifications()
                print("Notification permission granted.")
            } else {
                print("Notification permission was not granted.")
            }
        }
    }
}

Call this function from an appropriate point in the user experience, such as after explaining why notifications are useful. Avoid repeatedly prompting users who have already made a permission choice.

11.2 Understanding Permission Results

Result Meaning Recommended behavior
Granted The user authorized the requested notification options. Register for remote notifications and continue setup.
Denied The user declined notification permission. Respect the decision and offer Settings guidance when appropriate.
Error The authorization request returned an error. Handle the error and investigate the cause.

12. Understanding APNs Device Tokens and FCM Registration Tokens

APNs and FCM use different identifiers. Understanding their roles is essential for debugging notification delivery.

  • APNs device token: An Apple-issued token associated with the app's registration with APNs on a device.
  • FCM registration token: A Firebase-generated identifier used to target a particular app instance for FCM messaging.
  • Firebase Installation ID (FID): An identifier for a Firebase installation. It is not interchangeable with an APNs device token.

In common FCM iOS integrations, the messaging SDK supplies the FCM registration token through its delegate callback. Store it on a trusted backend only when needed for your application. Tokens can change, so update your backend whenever the SDK reports a new token.

12.1 Updating the Token on Your Server

func messaging(
    _ messaging: Messaging,
    didReceiveRegistrationToken fcmToken: String?
) {
    guard let token = fcmToken else {
        return
    }

    // Example only:
    // Send the current token to your authenticated backend.
    // Associate it with the signed-in user or installation.
    // Replace older token values when a new token is reported.
    print("FCM token updated.")
}

Do not treat a device token as proof of a user's identity. When users sign in or sign out, ensure that the backend maintains the correct relationship between the app installation, the authenticated account, and notification preferences.

13. Receiving Notifications in the Foreground

When a notification arrives while the app is active, iOS normally gives the app an opportunity to decide how it should be presented. The UNUserNotificationCenterDelegate method willPresent can specify whether to show a banner, play a sound, or update the badge.

func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler:
        @escaping (UNNotificationPresentationOptions) -> Void
) {
    let content = notification.request.content

    print("Foreground notification received: \(content.title)")

    completionHandler([.banner, .sound, .badge])
}

Choose presentation options that fit your application. For example, a messaging app may show a banner while a user is viewing another conversation, but avoid displaying duplicate alerts if the same information is already visible on screen.

14. Handling a User Tapping a Notification

When a user taps a notification, the notification-center delegate receives the response. The application can inspect the payload and open the relevant screen, such as an order detail, chat conversation, or announcement.

func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
) {
    let userInfo = response.notification.request.content.userInfo

    if let type = userInfo["type"] as? String {
        switch type {
        case "order":
            // Navigate to the order screen after app state is ready.
            print("Open order details.")

        case "chat":
            // Navigate to the appropriate conversation.
            print("Open chat conversation.")

        default:
            print("Open the app's default screen.")
        }
    }

    completionHandler()
}

Validate all payload values before using them. Do not trust a notification payload as authorization to access private information. The destination screen should verify the user's authentication and access permissions independently.

15. Notification Payload Structure

A push notification can include display content and custom data. A notification payload contains information that iOS can use to display an alert, while custom data allows the app to decide what content or action is relevant.

15.1 Example Notification and Data Payload

{
  "message": {
    "token": "FCM_REGISTRATION_TOKEN",
    "notification": {
      "title": "Order Update",
      "body": "Your order has been shipped."
    },
    "data": {
      "type": "order",
      "orderId": "ORDER_123"
    }
  }
}

This illustrates the general structure of a message sent using the FCM HTTP v1 API. Replace the placeholder token with a valid registration token and send the request from a trusted server using appropriate authorization. Never embed server credentials or service-account private keys in the iOS app.

15.2 Notification vs Data Messages

Message type Purpose Typical use
Notification message Provides title and body content for a user-visible notification. Announcements, delivery updates, reminders.
Data message Provides application-specific key-value data for handling by app logic. Refresh hints, routing metadata, sync triggers.
Combined message Includes notification content and custom data. Display an alert and identify the destination screen.

Delivery and execution behavior depends on the payload, app state, operating-system rules, permissions, and background execution limits. Do not assume that every data message will cause the app to execute immediately.

16. Sending a Test Notification from Firebase Console

The Firebase Console is a convenient way to verify that the basic push notification configuration works.

  1. Run the iOS application on a supported test device.
  2. Grant notification permission when prompted.
  3. Confirm that the app has registered for remote notifications.
  4. Open the Firebase Console and select your project.
  5. Navigate to the Firebase Messaging or messaging campaign interface.
  6. Create a notification campaign or test message.
  7. Enter a notification title and body.
  8. Select the option to send a test message, if available in the interface.
  9. Enter the current FCM registration token for the test app instance.
  10. Send the test notification and observe the device.
  11. Test with the app in the background, then separately test foreground handling.

A successful test confirms that the basic configuration can deliver a message. For production applications, also test token refresh, permission denial, app navigation, account changes, and delivery under realistic network conditions.

17. Testing Push Notifications in Different App States

App state What to test Expected considerations
Foreground Receive a message while the app is open. The notification delegate can choose the presentation behavior.
Background Send a notification while the app is not active. Visible notification presentation depends on permission and payload.
Terminated Send a notification when the app is not running. Test user-visible delivery and the app launch flow after a tap.
Permission denied Disable notification permission. The app should gracefully explain how to enable notifications in Settings.
Network unavailable Temporarily disconnect the device. Do not assume immediate delivery; handle later synchronization safely.
Token refreshed Simulate or observe a registration-token update. Verify the backend replaces the old token.

18. Troubleshooting Common Problems

18.1 Notifications Are Not Received

  • Verify that the app's bundle identifier matches the Firebase iOS app registration.
  • Confirm that Push Notifications capability is enabled in Xcode.
  • Check that the APNs authentication key and associated identifiers are configured correctly in Firebase.
  • Confirm that the user has allowed notifications in iOS Settings.
  • Verify that the application is registering for remote notifications.
  • Check whether the current FCM registration token is valid and up to date.
  • Test using a supported device and a reliable network connection.

18.2 Firebase Configuration Errors

  • Confirm that GoogleService-Info.plist belongs to the intended Firebase project.
  • Verify that the configuration file is included in the correct Xcode target.
  • Check that FirebaseApp.configure() runs before messaging APIs are used.
  • Ensure that the Firebase Messaging SDK is installed and linked correctly.

18.3 Notifications Arrive Only in the Background

  • Implement UNUserNotificationCenterDelegate correctly.
  • Set UNUserNotificationCenter.current().delegate during app initialization.
  • Implement willPresent and return the appropriate presentation options.
  • Check that the delegate object remains available for the required lifetime.

18.4 APNs Registration Fails

  • Check the selected Apple Developer team and signing settings.
  • Verify that the app identifier and provisioning configuration support push notifications.
  • Review the error returned by didFailToRegisterForRemoteNotificationsWithError.
  • Check the network, device environment, and current Apple Developer configuration.

18.5 Notifications Stop After Reinstallation

App reinstallation or other installation lifecycle events can lead to a new messaging registration token. Use the Firebase Messaging delegate to receive token updates and synchronize the current token with the backend rather than relying on a permanently fixed value.

19. Security Best Practices

  • Never place Firebase service-account credentials or server authorization secrets inside the iOS app.
  • Send privileged FCM requests from a trusted backend or an appropriately secured cloud function.
  • Protect notification registration data stored on your server.
  • Associate registration tokens with authenticated users only through a secure backend workflow.
  • Remove or disassociate tokens when a user signs out or uninstalls the app, where appropriate to your architecture.
  • Validate all notification payload values before navigating or performing actions.
  • Do not include passwords, access tokens, payment details, or other sensitive information in notification text.
  • Ask for notification permission in a clear and respectful way.
  • Allow users to manage notification preferences and unsubscribe from optional categories.
  • Use topic subscriptions only for suitable use cases and avoid exposing private user information through public or broadly accessible topics.
  • Keep Firebase SDKs updated and review official release notes for relevant changes.

20. Performance and User Experience Best Practices

  • Send relevant notifications instead of excessive messages.
  • Use clear, concise titles and notification bodies.
  • Include custom data only when the application needs it.
  • Handle duplicate messages safely when the business workflow requires it.
  • Use notification categories and actions where they improve the experience.
  • Ensure notification taps open the correct screen without creating duplicate navigation stacks.
  • Keep background work short and respect iOS background execution limits.
  • Measure delivery and user engagement through appropriate analytics.
  • Provide a useful in-app experience even when notifications are disabled.

21. Practical Project: Order Update Notification App

Build a small iOS application that receives notifications about order status changes. The project demonstrates Firebase configuration, APNs integration, permission handling, and notification navigation.

Project Requirements

  • Create an iOS app using Swift or SwiftUI.
  • Connect the app to a Firebase project.
  • Enable Push Notifications in Xcode.
  • Configure an APNs authentication key in Firebase.
  • Request notification permission from the user.
  • Register the app for remote notifications.
  • Receive an FCM registration token and synchronize it with a test backend when needed.
  • Send a test notification containing an order identifier.
  • Open the order details screen when the notification is tapped.
  • Test foreground, background, and permission-denied behavior.

Expected Result

The application should be able to receive a correctly configured push notification, display it when allowed by iOS, and navigate to the relevant order screen when the user taps the notification. If permission is denied or delivery fails, the app should remain usable and provide an appropriate fallback.

22. Practice Exercises

  1. Create a Firebase project and register an iOS application.
  2. Install Firebase Core and Firebase Messaging using Swift Package Manager.
  3. Enable Push Notifications in the Xcode target.
  4. Create and upload an APNs authentication key.
  5. Implement a notification permission request.
  6. Implement the messaging delegate and observe token updates.
  7. Send a test notification from Firebase Console.
  8. Implement foreground notification presentation.
  9. Handle notification taps using a custom payload.
  10. Document and resolve at least three notification setup issues.

23. Interview Questions and Answers

Q1. What is a push notification?

A push notification is a message delivered to an app through a remote notification service, allowing users to receive updates without actively opening the application.

Q2. What is Firebase Cloud Messaging?

Firebase Cloud Messaging is a service that enables developers to send messages and notifications to registered app instances across supported platforms.

Q3. What is APNs?

Apple Push Notification service is Apple's infrastructure for delivering remote notifications to Apple devices.

Q4. Why does FCM need APNs on iOS?

FCM integrates with APNs to deliver remote notifications through Apple's notification delivery system.

Q5. What is the purpose of an APNs authentication key?

It provides credentials that allow Firebase to authenticate with APNs for the relevant Apple Developer team and app configuration.

Q6. What is the difference between an APNs device token and an FCM registration token?

The APNs token identifies the app's registration with Apple's notification service, while the FCM registration token identifies an app instance for targeting through Firebase Cloud Messaging.

Q7. Why should an app request notification permission?

iOS requires user authorization for ordinary user-visible alert, sound, and badge notifications.

Q8. What is the purpose of UNUserNotificationCenterDelegate?

It lets the app respond to notification presentation and user interactions, including handling notifications while the app is active.

Q9. What is the purpose of MessagingDelegate?

It provides callbacks for Firebase Messaging events, including updates to the FCM registration token.

Q10. Why can an FCM registration token change?

Tokens may change during installation lifecycle events or when Firebase refreshes the registration. The app should update its backend when it receives a new token.

Q11. How can you test a notification?

Run the app on a supported device, grant permission, obtain the current FCM registration token, and send a test notification from Firebase Console.

Q12. What is a notification payload?

It is the message data delivered to the app. It may contain visible notification content, custom key-value data, or both.

Q13. How do you handle a notification tap?

Implement the notification-center response delegate, validate the payload, and navigate to the appropriate screen after the app is ready.

Q14. Why should server credentials not be included in an iOS app?

Client apps can be inspected or reverse-engineered. Privileged credentials must remain in a trusted server environment.

Q15. Are background data messages guaranteed to run immediately?

No. Background execution and message delivery depend on iOS rules, payload configuration, app state, and system conditions.

24. Quick Revision Checklist

  • Firebase project created and iOS app registered.
  • Correct GoogleService-Info.plist added to the target.
  • Firebase Core and Firebase Messaging SDKs installed.
  • Push Notifications capability enabled.
  • APNs authentication key uploaded to Firebase.
  • Notification permission requested appropriately.
  • Remote notification registration implemented.
  • Messaging delegate configured to receive token updates.
  • Foreground presentation and notification-tap handling implemented.
  • Test notification successfully received on a supported device.
  • Token synchronization and payload validation considered.
  • Server credentials kept out of the client application.

25. Official Learning Resources

26. Conclusion

Implementing push notifications with Firebase Cloud Messaging and APNs is an important skill for iOS developers. A reliable implementation requires correct Firebase configuration, Apple Developer credentials, notification permission handling, remote notification registration, and appropriate foreground and background behavior.

By completing the practical project and exercises in these notes, learners can build a foundation for adding notifications to messaging apps, e-commerce applications, educational platforms, and other iOS products. Always test the full notification flow on a supported device and follow the latest Firebase and Apple documentation when preparing an app for production.

Explore more iOS training: iOS App Development Course | Register for a Course Demo | JustAcademy

Previous Next
whatsapp